//
//  TTOAuthViewController.swift
//  NewWeiBo
//
//  Created by 吴天益 on 2017/7/23.
//  Copyright © 2017年 ttt. All rights reserved.
//

import UIKit

//跳转第三方请求参数
let appKey: String = "1917557566"
let appSecret: String = "70449dccfb59766835f81fe8c5e54fa6"
let redirect_uri: String = "http://www.itcast.cn"

class TTOAuthViewController: UIViewController {
    //实例化网络加载单例
    var netWorkTool = TTNetWorkTool.shareTool
    
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        view = webView
        
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(back))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoSet))

        setupWebView()
    }
    
    
    //MARK: - item点击方法
    func autoSet(){
        
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '13913775639';document.getElementById('passwd').value = '19930822wu';document.getElementById('passwd').focus()")
    }
    
    func back(){
        self.dismiss(animated: true, completion: nil)
    }
    
    //MARK: - webView设置
    func setupWebView(){

        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirect_uri)"
        
        webView.loadRequest(URLRequest(url: URL(string: urlStr)!))
        
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}


extension TTOAuthViewController:UIWebViewDelegate{
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlStr = request.url?.absoluteString
        
        print(urlStr!)
        
        //判断是否有回调也前缀
        if urlStr!.hasPrefix(redirect_uri + "/?code=") {
            let str = redirect_uri + "/?code="
            //截取授权码
            let ShouQuanStr = urlStr?.substring(from: str.endIndex)
            //发送获取令牌
            netWorkTool.requestLinPaiWithShouQuanMa(shouQuanMa: ShouQuanStr, backClosure: { (response, error) in
                if error != nil{
                    print(error!)
                    return
                }
                
                
                //没错误,然后获取令牌
                let dict = response as! [String: Any]
                
//                print(dict)
//                let a = dict["uid"] as! Int64
//                print(a)
                
                let userAccountModel = TTUserAccountModel(dict:dict)
//                userAccountModel?.access_token = dict["access_token"] as? String
//                userAccountModel?.expires_in = dict["expires_in"] as! Int
//                userAccountModel?.uid = dict["uid"] as! Int64
                
                
//                print(userAccountModel.access_token)
                
                //发送请求获取用户信息
                self.netWorkTool.requestUserMessageWithLinPai(linPai: userAccountModel.access_token,uid: (userAccountModel.uid),backClosure: { (response, error) in
                    if error != nil{
                        print(error!)
                        return
                    }
                    //获取用户信息
                    let dict2 = response as! [String: Any]
                    
                    userAccountModel.name = dict2["name"] as? String
                    userAccountModel.avatar_large = dict2["avatar_large"] as? String
                    
                    TTUserAccountViewModel.shareViewModel.userAccountModel = userAccountModel
                    
//                    print(userAccountModel.avatar_large)
                    
                    //存储用户信息
                    userAccountModel.saveUserAccount()
                    
                    //销毁模态控制器
                    self.dismiss(animated: false, completion: { 
                        //准备跳转到欢迎界面//发送通知
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: switchWindowRootController), object: self)
                    })
   
                })
                
            })
            //只需要获取授权码,不要加载回调页
            return false
        }
        
        
        
        return true
    }
    
    
}
